import os
import plistlib
import shutil
import subprocess
import sys

if sys.platform == "darwin" :
    from macholib.MachOStandalone import MachOStandalone
    import macholib.util

def deploy_for_darwin():
    app_name = "BabelPod"
    app_dir = "{0}.app".format(app_name)
    contents_dir = os.path.join(app_dir, "Contents")
    executable_dir = os.path.join(contents_dir, "MacOS")
    frameworks_dir = os.path.join(contents_dir, "Frameworks")
    
    # Install executable
    if not os.path.isdir(executable_dir) :
        os.makedirs(executable_dir)
    shutil.copy(sys.argv[1], executable_dir)
    
    # Make standalone executable
    if not os.path.isdir(frameworks_dir) :
        os.makedirs(frameworks_dir)
    files = MachOStandalone(app_dir).run()
    macholib.util.strip_files(files)
    
    # Deploy Qt plugins
    subprocess.call(["macdeployqt", app_dir])

    # Create info file
    if not os.path.isdir(contents_dir) :
        os.makedirs(contents_dir)    
    properties = {
        "CFBundleName" : app_name,
        "CFBundleDisplayName" : app_name,
        "CFBundleIdentifier" : "babelpod",
        "CFBundleVersion" : "0.1",
        "CFBundleShortVersionString" : "0.1",
        "CFBundleShortVersionString" : "10.5.0",
        "CFBundlePackageType" : "APPL",
        "CFBundleExecutable" : "babelpod"
    }
    plistlib.writePlist(properties, os.path.join(contents_dir, "Info.plist"))
    
    # Create .dmg
    subprocess.call(["hdiutil", "create", 
                     "{0}.dmg".format(app_name) , "-srcfolder", app_dir, 
                     "-format", "UDBZ", "-volname", app_name])

if __name__ == "__main__" :
    if sys.platform == "darwin" :
        deploy_for_darwin()